require('es6-promise').polyfill();

import axios from 'axios'

export function createMessageHandler() {
  return {
    type: 'CREATE_SUBSCRIBE_MESSAGE_HANDLER'
  }
}


function loadMessageHandler(data) {
  return {
    type: 'LOAD_SUBSCRIBE_MESSAGE_HANDLER',
    data
  }
}

function errorAction(error) {
  return {
    type: 'ERROR_SUBSCRIBE_MESSAGE_HANDLER',
    error
  }
}

export function apiMsgAction(msg) {
  return {
    type: 'API_MSG',
    msg
  }
}


export function loadMessageHandlerAsync(data) {
  return function(dispatch) {
    return axios.post('/api/messageHandler/subscribe', data).then(
      resp => dispatch(loadMessageHandler(resp.data)),
      error => dispatch(apiMsgAction(error.data.errMsg))
    );
  };
}

export function createMessageHandlerAsync(data) {
  return function(dispatch) {
    return axios.post('/api/messageHandler/createSubscribe', data)
    .then(resp => dispatch(apiMsgAction("保存成功!")),
          error => dispatch(apiMsgAction(error.data.errMsg))
        )
  }
}

export function deleteMessageHandlerAsync(data) {
  return function(dispatch) {
    return axios.post('/api/messageHandler/delete', data)
    .then(resp => dispatch(loadMessageHandlerAsync({appId: data.appId})),
          error => dispatch(apiMsgAction(error.data.errMsg))
        )
  }
}
